package com.will.client;


import com.will.client.adapter.ClientChannelHandlerAdapter;
import com.will.entity.MethodInvokeMeta;
import com.will.entity.NullWritable;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import io.netty.handler.codec.LengthFieldPrepender;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


/**
 * @author 杨明智
 * @version:1.0
 * @create 2019年01月10日 4:21 PM
 * @description
 **/
public class CustomChannelInitializer extends ChannelInitializer<SocketChannel>{

    private Logger logger = LoggerFactory.getLogger(CustomChannelInitializer.class);

    private MethodInvokeMeta methodInvokeMeta;

    private Object response;

    public CustomChannelInitializer(MethodInvokeMeta methodInvokeMeta){
        if(!"toString".equals(methodInvokeMeta.getMethodName())){
            logger.info("[CustomChannelInitializer] 调用方法名：{}，入参：{},参数类型：{}，返回值类型{}"
                    , methodInvokeMeta.getMethodName()
                    , methodInvokeMeta.getArgs()
                    , methodInvokeMeta.getParameterTypes()
                    , methodInvokeMeta.getReturnType());
        }
        this.methodInvokeMeta=methodInvokeMeta;
    }

    @Override
    protected void initChannel(SocketChannel socketChannel){
        ChannelPipeline pipeline = socketChannel.pipeline();
        pipeline.addLast(new LengthFieldPrepender(2));
        pipeline.addLast(new LengthFieldBasedFrameDecoder(1024 * 1024, 0, 2, 0, 2));
//        pipeline.addLast(new ObjectCodec());
        pipeline.addLast(new ClientChannelHandlerAdapter(methodInvokeMeta, this));

    }

    public Object getResponse() {
        if (response instanceof NullWritable) {
            return null;
        }
        return response;
    }

    public void setResponse(Object response) {
        this.response = response;
    }
}
